package com.dc.base.network

import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object NetworkApi {

    private var mOkHttpClient: OkHttpClient? = null

    private lateinit var mBaseUrl: String

    private var retrofit: Retrofit? = null

    fun <T> createService(serviceClass: Class<T>, baseUrl: String): T {
        mBaseUrl = baseUrl
        return (retrofit ?: getRetrofit().also { retrofit = it }).create(serviceClass)
    }

    private fun getOkhttpClient(): OkHttpClient {
        val builder = OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        return builder.addInterceptor(interceptor).build().also {
            mOkHttpClient = it
        }
    }

    private fun getRetrofit(): Retrofit {
        val retrofit = Retrofit.Builder()
            .baseUrl(mBaseUrl)
            .client(mOkHttpClient?: getOkhttpClient())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        return retrofit
    }
}